package com.rd.config.security;

/**
 * @author qiufen
 * @version 1.0
 * @date 2023-10-27 11:04
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 JWT登录授权过滤器
 OncePerRequestFilter
 doFilterInternal该方法在每个请求中只执行一次。
 */
@Slf4j
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    /**jwt请求头 Authorization */
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    /** JWT 负载中拿到开头(自己设置) 前端传递json数据的开头  Bearer xxxxxxxxxxxxxxxxx */
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
            response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取请求头上的token值
        String authHeader = request.getHeader(tokenHeader);
        System.out.println("authHeader="+authHeader);
        //存在token
        if (null != authHeader && authHeader.startsWith(tokenHead)) {
            //去掉字符串中前缀  Bearer
            String authToken = authHeader.substring(tokenHead.length());
            log.info("去掉前缀的token值:{}",authToken);
            //解析token值,获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            log.info("解析token获取到用户名:{}",username);
            //token存在用户名但未登录
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                //登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证token是否有效，重新设置用户对象
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    log.info("jwt验证token值成功!");
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
